﻿using Assignment_3.Classes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Assignment_3.Feature___Booking
{
    public partial class UpdateBooking : System.Web.UI.Page
    {
        bool requiredFields = false;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                int bookingID = Convert.ToInt32(Request.QueryString["booking"]);
                int roomID = Convert.ToInt32(Request.QueryString["room"]);

                Booking b = DatabaseManager.ViewBookingByBID(bookingID);

                if (b != null)
                {
                    DateTime checkIn = b.Check_In_Date;
                    tbxCheckIn.Text = String.Format("{0:yyyy-MM-dd}", checkIn);
                    DateTime checkOut = b.Check_Out_Date;
                    tbxCheckOut.Text = String.Format("{0:yyyy-MM-dd}", checkOut);
                    ddlAdults.SelectedValue = b.No_Of_Adults.ToString();
                    ddlChildren.SelectedValue = b.No_Of_Children.ToString();
                }

                Room r = DatabaseManager.ViewRoomByRID(roomID);

                if (r != null)
                {
                    rblRoomType.SelectedValue = r.Room_Type;
                    ddlBedType.SelectedValue = r.Bed_Type;
                    if (r.Status != null)
                    {
                        if (r.Status.Equals("Occupied", StringComparison.OrdinalIgnoreCase))
                        {
                            ddlRoomsStatus.SelectedValue = r.Status;
                        }
                        else if (r.Status.Equals("Reserved", StringComparison.OrdinalIgnoreCase))
                        {
                            ddlRoomsStatus.SelectedValue = r.Status;
                        }
                        else if (r.Status.Equals("Vacant", StringComparison.OrdinalIgnoreCase))
                        {
                            ddlRoomsStatus.SelectedValue = r.Status;
                        }
                        else if (r.Status.Equals("Vacant & Cleaning", StringComparison.OrdinalIgnoreCase) || r.Status.Equals("Vacant&Cleaning", StringComparison.OrdinalIgnoreCase) || r.Status.Equals("Vacant and Cleaning", StringComparison.OrdinalIgnoreCase) || r.Status.Equals("Vacant Cleaning", StringComparison.OrdinalIgnoreCase))
                        {
                            ddlRoomsStatus.SelectedValue = r.Status;
                        }
                    }
                }

                Guest g = DatabaseManager.ViewGuestByBID(bookingID);

                if (g != null)
                {
                    tbxGuestName.Text = g.Name;
                    tbxPhoneNo.Text = g.Phone.ToString();
                    tbxEmail.Text = g.Email;
                    tbxAddress.Text = g.Address;
                    tbxPostalCode.Text = g.PostalCode.ToString();
                    tbxCountry.Text = g.Country;
                    rblPaymentType.SelectedValue = g.PaymentType;
                }

                if (g.PaymentType != null)
                {
                    if (g.PaymentType.Equals("Credit Card", StringComparison.OrdinalIgnoreCase))
                    {
                        Payment p = DatabaseManager.ViewPaymentByBID(bookingID);

                        tbxCardholder.Text = p.CardholderName;
                        tbxCreditCardNo.Text = p.CreditCardNo;
                        tbxExpiryDate.Text = p.ExpiryDate.ToString("yyyy-MM-dd");

                        tbxCardholder.Visible = true;
                        tbxCreditCardNo.Visible = true;
                        tbxExpiryDate.Visible = true;
                        imgBtnCal3.Visible = true;

                        lblCardholderName.Visible = true;
                        lblCreditCardNo.Visible = true;
                        lblExpiryDate.Visible = true;
                    }
                    else if (g.PaymentType.Equals("Cash", StringComparison.OrdinalIgnoreCase))
                    {
                        tbxCardholder.Visible = false;
                        tbxCreditCardNo.Visible = false;
                        tbxExpiryDate.Visible = false;
                        imgBtnCal3.Visible = false;

                        lblCardholderName.Visible = false;
                        lblCreditCardNo.Visible = false;
                        lblExpiryDate.Visible = false;
                    }
                }
            }
            panelMsg.Controls.Clear();
        }

        protected void rblPaymentType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rblPaymentType.SelectedValue == "Credit Card")
            {
                lblCardholderName.Visible = true;
                tbxCardholder.Visible = true;
                lblCreditCardNo.Visible = true;
                tbxCreditCardNo.Visible = true;
                lblExpiryDate.Visible = true;
                tbxExpiryDate.Visible = true;
                imgBtnCal3.Visible = true;
            }
            else
            {
                lblCardholderName.Visible = false;
                tbxCardholder.Visible = false;
                lblCreditCardNo.Visible = false;
                tbxCreditCardNo.Visible = false;
                lblExpiryDate.Visible = false;
                tbxExpiryDate.Visible = false;
                imgBtnCal3.Visible = false;
            }
        }

        protected void btnCommit_Click(object sender, EventArgs e)
        {
            Page.Validate();

            //if (rblPaymentType.SelectedValue == "Cash")
            //{
            //    RequiredFieldValidator9.IsValid = true;
            //    RequiredFieldValidator10.IsValid = true;
            //    RequiredFieldValidator11.IsValid = true;
            //}

            if (Page.IsValid)
            {
                int bookingID = Convert.ToInt32(Request.QueryString["booking"]);
                int roomID = Convert.ToInt32(Request.QueryString["room"]);
                int guestID = DatabaseManager.RetrieveGuestIDByBID(bookingID);

                Booking b2 = new Booking();
                b2.BookingID = Convert.ToInt32(bookingID);
                b2.Check_In_Date = Convert.ToDateTime(tbxCheckIn.Text);
                b2.Check_Out_Date = Convert.ToDateTime(tbxCheckOut.Text);
                b2.No_Of_Adults = Convert.ToInt32(ddlAdults.SelectedValue);
                b2.No_Of_Children = Convert.ToInt32(ddlChildren.SelectedValue);
                int successBooking = DatabaseManager.UpdateBooking(b2);

                Room r2 = new Room();
                r2.RoomID = roomID;
                r2.Room_Type = rblRoomType.SelectedValue;
                r2.Bed_Type = ddlBedType.SelectedValue;
                string status = "";

                if (ddlRoomsStatus.SelectedValue.Equals("Occupied", StringComparison.OrdinalIgnoreCase))
                {
                    status = "Occupied";
                }
                else if (ddlRoomsStatus.SelectedValue.Equals("Reserved", StringComparison.OrdinalIgnoreCase))
                {
                    status = "Reserved";
                }
                else if (ddlRoomsStatus.SelectedValue.Equals("Vacant", StringComparison.OrdinalIgnoreCase))
                {
                    status = "Vacant";
                }
                else if (ddlRoomsStatus.SelectedValue.Equals("Vacant & Cleaning", StringComparison.OrdinalIgnoreCase))
                {
                    status = "Vacant & Cleaning";
                }

                r2.Status = status;
                int successRoom = DatabaseManager.UpdateRoom(r2);

                Guest g2 = new Guest();
                g2.GuestID = guestID;
                g2.Name = tbxGuestName.Text;
                g2.Phone = Convert.ToInt32(tbxPhoneNo.Text);
                g2.Email = tbxEmail.Text;
                g2.Address = tbxAddress.Text;
                g2.PostalCode = Convert.ToInt32(tbxPostalCode.Text);
                g2.Country = tbxCountry.Text;
                g2.PaymentType = rblPaymentType.SelectedValue;
                int successGuest = DatabaseManager.UpdateGuest(g2);


                int successPayment = 0;
                //bool hasCreditCardPayment = false;
                if (rblPaymentType.SelectedValue.Equals("Credit Card", StringComparison.OrdinalIgnoreCase))
                {
                    Payment p2 = new Payment();
                    p2.GuestID = guestID;
                    p2.CardholderName = tbxCardholder.Text;
                    p2.CreditCardNo = tbxCreditCardNo.Text;
                    p2.ExpiryDate = Convert.ToDateTime(tbxExpiryDate.Text);
                    successPayment = DatabaseManager.UpdatePayment(p2);
                    //hasCreditCardPayment = true;
                }

                //if (hasCreditCardPayment)
                //{
                //    if (successBooking == 1 && successRoom == 1 && successGuest == 1 && successPayment == 1)
                //    {
                //        string jsPopup = "<script type='text/javascript'>" +
                //                "alert('Successfully Updated Booking!');" +
                //                "window.location.href = 'ViewBooking.aspx?booking=" +
                //                Request.QueryString["booking"] + "&room=" +
                //                Request.QueryString["room"] +
                //                "';" +
                //                "</script>";
                //        ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", jsPopup);
                //    }
                //}
                //else
                //{

                if (successBooking == 1)
                {
                    string jsPopup = "<script type='text/javascript'>" +
                            "alert('Successfully Updated Booking!');" +
                            "window.location.href = 'ViewBooking.aspx?booking=" +
                            Request.QueryString["booking"] + "&room=" +
                            Request.QueryString["room"] +
                            "';" +
                            "</script>";
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", jsPopup);
                }
            }
            else
            {
                string requiredValidationGroup = "bookingFields";
                foreach (BaseValidator validator in Page.Validators)
                {
                    if (validator.ValidationGroup == requiredValidationGroup)
                    {
                        bool valid = validator.IsValid;
                        if (valid)
                        {
                            validator.Validate();
                            valid = validator.IsValid;
                            validator.IsValid = true;
                        }
                        if (!valid)
                            requiredFields = true;
                    }
                }

                if (requiredFields)
                {
                    panelMsg.Controls.Clear();
                    Literal litMsg = new Literal();
                    litMsg.Text = "<h4 class='alert_error'>Error: You have not filled out some required information. Please review the page.</h4>";
                    panelMsg.Controls.Add(litMsg);
                }
            }
        }

        protected void btnDiscard_Click(object sender, EventArgs e)
        {
            int bookingID = Convert.ToInt32(Request.QueryString["booking"]);
            int roomID = Convert.ToInt32(Request.QueryString["room"]);
            Response.Redirect("ViewBooking.aspx?booking=" + bookingID + "&room=" + roomID);
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            panelMsg.Controls.Clear();
            Literal litMsg = new Literal();
            litMsg.Text = "<h4 class='alert_warning'>Warning: You will not be able to retrieve back! &nbsp;&nbsp; - Press 'Confirm Delete' if you wish to proceeed anyway.</h4>";
            panelMsg.Controls.Add(litMsg);

            btnDelete.Visible = false;
            btnConfirmDelete.Visible = true;
        }

        protected void btnConfirmDelete_Click(object sender, EventArgs e)
        {

            int bookingID = Convert.ToInt32(Request.QueryString["booking"]);
            int guestID = DatabaseManager.RetrieveGuestIDByBID(bookingID);

            int successPayment = 0;
            if (rblPaymentType.SelectedValue.Equals("Credit Card", StringComparison.OrdinalIgnoreCase))
            {
                successPayment = DatabaseManager.DeletePayment(guestID);
            }

            int successRoom = DatabaseManager.DeleteRoom(bookingID);
            int successBooking = DatabaseManager.DeleteBooking(bookingID);
            int successGuest = DatabaseManager.DeleteGuest(guestID);

            if (successGuest == 1 && successBooking == 1)
            {
                string jsPopup = "<script type='text/javascript'>" +
                    "alert('Successfully Deleted Booking!');" +
                    "window.location.href = 'RetrieveBookings.aspx';" +
                    "</script>";
                ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", jsPopup);
            }
        }
    }
}